package javaer.dev.manual.depthclone;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单类
 */
public class Order implements Cloneable , Serializable {
    private static final long serialVersionUID = 1L;


    private Long id;
    private String orderNo;
    private List<Item> itemList;

    public Order() {
    }

    public Order(Long id, String orderNo, List<Item> itemList) {
        this.id = id;
        this.orderNo = orderNo;
        this.itemList = itemList;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getOrderNo() {
        return orderNo;
    }

    public void setOrderNo(String orderNo) {
        this.orderNo = orderNo;
    }

    public List<Item> getItemList() {
        return itemList;
    }

    public void setItemList(List<Item> itemList) {
        this.itemList = itemList;
    }

    @Override
    public String toString() {
        return "{" +
                "id=" + id +
                ", orderNo='" + orderNo + '\'' +
                ", itemList=" + itemList +
                '}';
    }

    /**
     * 浅拷贝 , 即 Object.clone()
     */
/*    @Override
    public Object clone() throws CloneNotSupportedException {
        try {
            return (Order) super.clone();

        } catch (CloneNotSupportedException e) {
            // 不会调到这里
        }
        return null;
    }*/

    /**
     * 手动深拷贝
     */

    @Override
    protected Object clone() {
        try {
            Order order = (Order) super.clone();
            // 对每一个属性进行判断
            if (order.id != null) {
                order.id = new Long(id);
            }

            if (order.orderNo != null) {
                order.orderNo = new String(orderNo);
            }

            if (order.itemList != null) {
                List<Item> lists = new ArrayList<>();

                for (Item each : itemList) {
                    Item item = new Item();

                    Long id = each.getId();
                    if (id != null) {
                        item.setId(new Long(id));
                    }

                    Long itemId = each.getItemId();
                    if (itemId != null) {
                        item.setItemId(new Long(itemId));
                    }
                    String name = each.getName();
                    if (name != null) {
                        item.setName(name);
                    }

                    String desc = each.getDesc();
                    if (desc != null) {
                        item.setDesc(desc);

                    }

                    lists.add(item);

                }

                order.setItemList(lists);
            }

            return order;
        } catch (CloneNotSupportedException e) {

        }

        return null;
    }
}
